package com.pi.community.controller;

import com.alibaba.dubbo.rpc.RpcException;
import com.homelock.common.vo.Resp;
import com.homelock.domain.CommunityAdvDto;
import com.homelock.vo.CommunityInfoVo;
import com.pi.base.common.BasePage;
import com.pi.base.common.BaseResult;
import com.pi.base.common.SearchPage;
import com.pi.base.controller.BaseController;
import com.pi.base.util.FileTool;
import com.pi.base.util.JsonTool;
import com.pi.base.util.ValidUtil;
import com.pi.base.util.cache.RedisUtil;
import com.pi.base.util.transfer.windows.FileUtil;
import com.pi.base.vo.SelectVO;
import com.pi.community.common.CommunityConst;
import com.homelock.domain.query.ComOpenRecordQuery;
import com.pi.community.common.FtpFileConfig;
import com.pi.community.common.enumeration.TriggerTypeEnum;
import com.pi.community.dto.CommunityDto;
import com.pi.base.service.ISysGroupService;
import com.homelock.common.vo.PageResp;
import com.homelock.dubbo.service.CommunityManagerService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.Asserts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * 物业公司Controller
 *
 */
@Controller
@RequestMapping("/community")
public class CommunityController  extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(CommunityController.class);

    @Resource
    private ISysGroupService sysGroupService;
    /**
     * 引入服务提供者
     */
    @Resource(name = "communityManagerService")
    private CommunityManagerService communityManagerService;

    @ResponseBody
    @RequestMapping("adduser")
    public BaseResult addGroupUser(@RequestBody CommunityDto communityDto){
        return sysGroupService.addReCompanyWithGroup(communityDto);
    }

    @RequestMapping("alarm/list")
    public String list(ModelMap model) {
        // 报警分类
        List<SelectVO> typeList = new ArrayList<SelectVO>();
        for(TriggerTypeEnum s : TriggerTypeEnum.values()) {    //values()方法返回enum实例的数组
            SelectVO selectVO = new SelectVO();
            selectVO.setName(s.getName());
            selectVO.setValue(s.getCode());
            typeList.add(selectVO);
        }
     //   List<SysGroup> groupList = sysUserService.getGroupWithSubListByGroupId(groupId.toString());
        model.addAttribute("typeList", typeList);
        return "community/alarm/list";
    }

    @RequestMapping("adv/goadd")
    public String goAdvAdd() {
        return "community/household/advadd";
    }

    @RequestMapping("adv/golist")
    public String goAdvList() {
        return "community/household/advlist";
    }

    @RequestMapping("adv/goupdate")
    public String goAdvUdate() {
        return "community/household/advupdate";
    }

    @RequestMapping("adv/goinfo")
    public String goAdvInfo(ModelMap model, Long id,HttpSession httpSession) {
        String reCode = this.getLoginedUserInfo(httpSession).getItem1();
        Long communityId = 0L;
        try {
            communityId = Long.valueOf(reCode.substring(CommunityConst.COMMUNITY_PRE.length()));
            CommunityAdvDto advDto = communityManagerService.queryAdvById(id,communityId);
            model.addAttribute("adv",advDto);

        }catch (Exception e){
            logger.error("当前管理员的社区编号异常：" + reCode);
        }
        return "community/household/advinfo";
    }


    @RequestMapping("alarm/query")
    @ResponseBody
    public Object queryAlarmList(@ModelAttribute SearchPage searchPage, @RequestParam(required=false)String userName,
                                 @RequestParam(required=false)String recordType, HttpSession httpSession){
        logger.info("recordType:"+recordType);
        logger.info("userName:"+userName);

        searchPage.setPage((searchPage.getPage() == null) ? 1 : searchPage.getPage());
        searchPage.setRows((searchPage.getRows() == null) ? 0 : searchPage.getRows()); //默认查询全部
        // 查询当前登录管理员对应的物业id
        String reCode = this.getLoginedUserInfo(httpSession).getItem1();

        if(StringUtils.isBlank(reCode) || !reCode.startsWith(CommunityConst.COMMUNITY_PRE)){
            return new BasePage(0);
        }
        Long communityId = 0L;
        Integer opmode = null;
        try{
            communityId = Long.valueOf(reCode.substring(CommunityConst.COMMUNITY_PRE.length()));
        }catch (Exception e){
            logger.error("当前管理员的社区编号异常："+reCode);
            return new BasePage(0);
        }
        try{
            opmode = (recordType == null) ? null : Integer.valueOf(recordType);
        }catch (Exception e){
            logger.error("当前报警类型异常："+recordType);
        }
        ComOpenRecordQuery comOpenRecordQuery = new ComOpenRecordQuery();
        comOpenRecordQuery.setCommunityId(communityId);
        comOpenRecordQuery.setOpmode(opmode);
        comOpenRecordQuery.setLimit(searchPage.getRows());
        comOpenRecordQuery.setOffset(searchPage.getStartIndex());
        comOpenRecordQuery.setUserName(userName);
        try{
        PageResp pageResp = communityManagerService.queryPageAlarmListByCommunity(comOpenRecordQuery);
        return new BasePage<>(pageResp.getTotal(),pageResp.getRows());
        }catch (RpcException e){
            e.printStackTrace();
            return BaseResult.newErrorResult("远程服务调用失败");
        }
    }


    @RequestMapping("contact/goupdate")
    public String goUpdateContact(ModelMap model, HttpSession httpSession) {
        String reCode = this.getLoginedUserInfo(httpSession).getItem1();
        Long communityId = 0L;
        try {
            communityId = Long.valueOf(reCode.substring(CommunityConst.COMMUNITY_PRE.length()));
            CommunityInfoVo communityInfoVo = communityManagerService.queryById(communityId);
            model.addAttribute("community", communityInfoVo);
        } catch (Exception e) {
            logger.error("当前管理员的社区编号异常：" + reCode);
        }
        return "community/contact/update";
    }

    @RequestMapping("contact/update")
    @ResponseBody
    public BaseResult updateContact(@RequestParam(required=false)String contact, HttpSession httpSession) {
        logger.info("contact:" + contact);
        boolean check = ValidUtil.validateMobile(contact);
        if(!check){
            return BaseResult.newErrorResult("联系方式格式错误");
        }
        // 查询当前登录管理员对应的物业id
        String reCode = this.getLoginedUserInfo(httpSession).getItem1();
        Long communityId = 0L;
        try {
            communityId = Long.valueOf(reCode.substring(CommunityConst.COMMUNITY_PRE.length()));
        } catch (Exception e) {
            logger.error("当前管理员的社区编号异常：" + reCode);
            return BaseResult.newErrorResult("当前管理员的社区编号异常");
        }
        Resp resp = communityManagerService.updateCommunityContact(communityId, contact);
        if (resp.equalOk()) {
            return BaseResult.newSuccessResult();
        }
        return BaseResult.newErrorResult(resp.getMsg());
    }

    @RequestMapping("adv/uploadOnePic")
    @ResponseBody
    public BaseResult fileUpload(String inputId, MultipartHttpServletRequest request, HttpSession httpSession) {
        try {
            String reCode = this.getLoginedUserInfo(httpSession).getItem1();
            // 拿到文件
            MultipartFile realPicFile = request.getFile(inputId);
            String dirPath = request.getSession().getServletContext().getRealPath("/") + "advupload/";
            String orginName = realPicFile.getOriginalFilename();
            String picType = orginName.substring(orginName.lastIndexOf("."));
            String fileName = System.currentTimeMillis()+ picType;
            //  String remoteUrl = FileUtil.transferToRemote(FtpFileConfig.host,FtpFileConfig.username,FtpFileConfig.password,FtpFileConfig.parentFolder,realPicFile.getInputStream(),reCode);
            boolean uploadFlag = FileTool.fileUpload(realPicFile,dirPath,fileName);
            if(uploadFlag){
                String restoreimg = "http://localhost:8081/pi_admin/"+"advupload/"+fileName;
                // redis存储
                return BaseResult.newSuccessResult("上传成功",restoreimg);
            }
            return BaseResult.newErrorResult("图片上传失败");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return BaseResult.newErrorResult("图片上传失败");
    }

    @RequestMapping("adv/addadv")
    @ResponseBody
    public BaseResult addadvinfo(@RequestParam(required=true)String hiddenImgValue1,@RequestParam(required=true)String hiddenImgValue2, HttpSession httpSession) {
        // 查询当前登录管理员对应的物业id
        String reCode = this.getLoginedUserInfo(httpSession).getItem1();
        Long communityId = 0L;
        try {
            communityId = Long.valueOf(reCode.substring(CommunityConst.COMMUNITY_PRE.length()));
        } catch (Exception e) {
            logger.error("当前管理员的社区编号异常：" + reCode);
            return BaseResult.newErrorResult("当前管理员的社区编号异常");
        }
        logger.info("大图：{}",hiddenImgValue1);
        logger.info("小图：{}",hiddenImgValue2);
        logger.info("社区id:{}",communityId);
        CommunityAdvDto dto = new CommunityAdvDto();
        dto.setPicUrl(hiddenImgValue1);
        dto.setThumbnailUrl(hiddenImgValue2);
        dto.setCommunityId(communityId);
        Resp resp = communityManagerService.addCommunityAdv(dto);
        if (resp.equalOk()) {
            return BaseResult.newSuccessResult();
        }
        return BaseResult.newErrorResult(resp.getMsg());
    }

    @RequestMapping("adv/updateadv")
    @ResponseBody
    public BaseResult updateadvinfo(@RequestParam(required=true) Long id,@RequestParam(required=true)String hiddenImgValue1,@RequestParam(required=true)String hiddenImgValue2, HttpSession httpSession) {
        Asserts.notNull(id,"广告信息id");
        // 查询当前登录管理员对应的物业id
        String reCode = this.getLoginedUserInfo(httpSession).getItem1();
        Long communityId = 0L;
        try {
            communityId = Long.valueOf(reCode.substring(CommunityConst.COMMUNITY_PRE.length()));
        } catch (Exception e) {
            logger.error("当前管理员的社区编号异常：" + reCode);
            return BaseResult.newErrorResult("当前管理员的社区编号异常");
        }
        logger.info("大图：{}",hiddenImgValue1);
        logger.info("小图：{}",hiddenImgValue2);
        logger.info("社区id:{}",communityId);
        logger.info("广告id:{}",id);
        CommunityAdvDto dto = new CommunityAdvDto();
        dto.setId(id);
        dto.setPicUrl(hiddenImgValue1);
        dto.setThumbnailUrl(hiddenImgValue2);
        dto.setCommunityId(communityId);
        Resp resp = communityManagerService.updateCommunityAdv(dto);
        if (resp.equalOk()) {
            return BaseResult.newSuccessResult();
        }
        return BaseResult.newErrorResult(resp.getMsg());
    }

    @RequestMapping("adv/deladv")
    @ResponseBody
    public BaseResult deladvinfo(@RequestParam(required=true) Long id, HttpSession httpSession) {
        Asserts.notNull(id,"广告信息id");
        // 查询当前登录管理员对应的物业id
        String reCode = this.getLoginedUserInfo(httpSession).getItem1();
        Long communityId = 0L;
        try {
            communityId = Long.valueOf(reCode.substring(CommunityConst.COMMUNITY_PRE.length()));
        } catch (Exception e) {
            logger.error("当前管理员的社区编号异常：" + reCode);
            return BaseResult.newErrorResult("当前管理员的社区编号异常");
        }
        Resp resp = communityManagerService.deleteCommunityAdv(id);
        if (resp.equalOk()) {
            return BaseResult.newSuccessResult();
        }
        return BaseResult.newErrorResult(resp.getMsg());
    }

    @RequestMapping("adv/query")
    @ResponseBody
    public Object querAdvList(@ModelAttribute SearchPage searchPage, HttpSession httpSession){
         searchPage.setPage((searchPage.getPage() == null) ? 1 : searchPage.getPage());
        searchPage.setRows((searchPage.getRows() == null) ? 0 : searchPage.getRows()); //默认查询全部
        // 查询当前登录管理员对应的物业id
        String reCode = this.getLoginedUserInfo(httpSession).getItem1();

        if(StringUtils.isBlank(reCode) || !reCode.startsWith(CommunityConst.COMMUNITY_PRE)){
            return new BasePage(0);
        }
        Long communityId = 0L;
        try{
            communityId = Long.valueOf(reCode.substring(CommunityConst.COMMUNITY_PRE.length()));
        }catch (Exception e){
            logger.error("当前管理员的社区编号异常："+reCode);
            return new BasePage(0);
        }
        ComOpenRecordQuery comOpenRecordQuery = new ComOpenRecordQuery();
        comOpenRecordQuery.setCommunityId(communityId);
        comOpenRecordQuery.setLimit(searchPage.getRows());
        comOpenRecordQuery.setOffset(searchPage.getStartIndex());
        try{
            PageResp pageResp = communityManagerService.queryPageAdv(comOpenRecordQuery);
            return new BasePage<>(pageResp.getTotal(),pageResp.getRows());
        }catch (RpcException e){
            e.printStackTrace();
            return BaseResult.newErrorResult("远程服务调用失败");
        }

    }
}
